import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'dart:ui';

import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/video_upload_success_bean.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/update_terminal_play_list_status_event.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/index/bean/update_terminal_play_list_status_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_upload_service.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_matisse_utils.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:path_provider/path_provider.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';
import 'package:vg_base/vg_widget_lib.dart';
import 'package:video_thumbnail/video_thumbnail.dart';

class MediaLibraryIndexService {
  ///App公司添加播放资源库
  static const String _UPLOAD_MEDIA_LIBRARY_API =
     ServerApi.BASE_URL + "app/appUploadComPicurl";

  ///App公司添加播放资源库
  static const String UPLOAD_MEDIA_LIBRARY_WITH_TERMINAL_SETTINGS_API =
     ServerApi.BASE_URL + "app/appNewSavePicByhsn";

  ///App公司添加播放资源库 多图同时上传
  static const String MULTI_UPLOAD_MEDIA_LIBRARY_WITH_TERMINAL_SETTINGS_API =
     ServerApi.BASE_URL + "app/appNewUploadPicByhsn";

  List<UploadMediaLibraryItemBean> _uploadList;

  String _hsns;
  String _startDay;
  String _endDay;
  String _allflg; //00 部分终端 01 全部终端
  String _title;
  String _content;
  String _waterflg;//00没有水印 01有水印
  String _logoflg;//00显示logo 01不显示
  BuildContext _context;

  ///设置值
  MediaLibraryIndexService setList(
      List<UploadMediaLibraryItemBean> folderList) {
    if (folderList == null || folderList.isEmpty) {
      return null;
    }
    _uploadList = folderList;
    return this;
  }

  ///设置上传列表，播放终端，开始日期，结束日期
  ///waterflg 00没有水印 01有水印
  MediaLibraryIndexService setListAndSettings(
      BuildContext context,
      List<UploadMediaLibraryItemBean> folderList,
      String hsns,
      String startDay,
      String endDay,
      String allflg,
      {String title, String content, String waterflg, String logoflg}
      ) {
    if (folderList == null || folderList.isEmpty) {
      return null;
    }
    _context = context;
    _uploadList = folderList;
    _hsns = hsns;
    _startDay = startDay;
    _endDay = endDay;
    if(VgRoleUtils.isCommonAdmin(UserRepository.getInstance().getCurrentRoleId())){
      //普通管理员上传文件时，就算选择了全部终端，是否选择全部终端的标识也应该是“否”
      _allflg = "00";
    }else{
      _allflg = allflg;
    }

    if(StringUtils.isNotEmpty(title)){
      _title = title;
    }
    if(StringUtils.isNotEmpty(content)){
      _content = content;
    }
    if(StringUtils.isNotEmpty(waterflg)){
      _waterflg = waterflg;
    }
    if(StringUtils.isNotEmpty(logoflg)){
      _logoflg = logoflg;
    }
    return this;
  }

  ///多图上传
  void multiUpload(VgBaseCallback callback)async{
    if (_uploadList == null || _uploadList.isEmpty) {
      callback?.onError("需要上传的数据为空");
      return;
    }
    VgHudUtils.show(AppMain.context, "正在上传");
    try {
      for (UploadMediaLibraryItemBean item in _uploadList) {
        item = await _manageFolder(item);
      }
    } catch (e) {
      callback?.onError("处理出现异常");
      print("上传报错:$e");
      return;
    }
    _uploadList.removeWhere((element) => element == null);
    List<Future<UploadMediaLibraryItemBean>> futureList = List();
    for (UploadMediaLibraryItemBean item in _uploadList) {
      futureList.add(_httpMultiFolder(item, onGetNewFileLength: (value){
        item.folderStorage = value;
      }));
    }
    Future.wait(futureList)
      ..then((List<UploadMediaLibraryItemBean> list) {
        List<PicListItemBean> picList = new List();
        list.forEach((element) {
          PicListItemBean picListItemBean = new PicListItemBean(
            picurl: element.netUrl??"",
            type: element.mediaType?.getParamsValue()??"",
            picname: element.folderName??"",
            picsize: element.getSize()??"",
            picstorage: element.getStorage()??"",
            videotime: element.videoDuration??0,
            videopic: element.videoNetCover??"",
              videoid: element.videoid??""
          );
          picList.add(picListItemBean);
        });
        String picjson = "";
        if(picList.isNotEmpty){
          picjson = json.encode(picList);
        }
        //接口
        Map<String, dynamic> paramsMap = {
          "authId": UserRepository.getInstance().authId ?? "",
          "allflg": _allflg ?? null,
          "endday": _endDay ?? null,
          "hsns": _hsns ?? null,
          "picjson": picjson ?? "",
          "startday": _startDay ?? null,
          "logoflg": _logoflg ?? "01",
          "subtitle": _content ?? null,
          "title": _title ?? null,
          "waterflg": _waterflg ?? "01",
        };

        print("准备多图上传测试参数: ${paramsMap}");
        VgHttpUtils.get(MULTI_UPLOAD_MEDIA_LIBRARY_WITH_TERMINAL_SETTINGS_API,
            params: paramsMap,
            callback: BaseCallback(onSuccess: (val) {
              callback?.onSuccess(list);
              getUpdateTerminalPlayListStatus(_hsns);
            }, onError: (msg) {
              callback?.onError(msg);
            }));
      }).catchError((e) {
        callback?.onError("上传失败");
      });

  }

  void upload(VgBaseCallback callback) async {
    if (_uploadList == null || _uploadList.isEmpty) {
      callback?.onError("需要上传的数据为空");
      return;
    }
    VgHudUtils.show(AppMain.context, "正在上传");
    try {
      for (UploadMediaLibraryItemBean item in _uploadList) {
        item = await _manageFolder(item);
      }
    } catch (e) {
      callback?.onError("处理出现异常");
      print("上传报错:$e");
      return;
    }
    _uploadList.removeWhere((element) => element == null);
    print("打印需要上传的信息：$_uploadList");
    List<Future<UploadMediaLibraryItemBean>> futureList = List();
    for (UploadMediaLibraryItemBean item in _uploadList) {
      futureList.add(_httpFolder(item, onGetNewFileLength: (value){
        item.folderStorage = value;
      }));
    }
    Future.wait(futureList)
      ..then((List<UploadMediaLibraryItemBean> list) {
        callback?.onSuccess(list);
        // getUpdateTerminalPlayListStatus(_hsns);
      }).catchError((e) {
        print("个别文件上传失败:" + e.toString());
        callback?.onError("个别文件上传失败");
      });
  }

  ///查询终端获取资源是否成功
  void getUpdateTerminalPlayListStatus(String hsn) {
    String authId = UserRepository.getInstance().authId;
    if (StringUtils.isEmpty(authId)) {
      return;
    }

    ///网络请求
    VgHttpUtils.get(NetApi.UPDATE_TERMINAL_PLAY_LIST_STATUS_API,
        params: {
          "authId": authId ?? "",
          "hsn": hsn ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          UpdateTerminalPlayListStatusBean bean =
          UpdateTerminalPlayListStatusBean.fromMap(val);
          if (bean != null) {
            VgEventBus.global.send(new UpdateTerminalPlayListStatusEvent(
                bean?.data?.obtainflg ?? "", hsn));
          }
        }, onError: (msg) {
          VgToastUtils.toast(AppMain.context, msg);
        }));
  }

  ///处理文件
  Future<UploadMediaLibraryItemBean> _manageFolder(
      UploadMediaLibraryItemBean item) async {
    if (item == null ||
        item.mediaType == null ||
        StringUtils.isEmpty(item.localUrl)) {
      return null;
    }
    if (item.isImage()) {
      return _decodeImage(item);
    }
    if (item.isVideo()) {
      return await _decodeVideo(item);
    }
    return null;
  }

  UploadMediaLibraryItemBean _decodeImage(UploadMediaLibraryItemBean item) {
    if (item == null ||
        item.mediaType == null ||
        StringUtils.isEmpty(item.localUrl)) {
      return null;
    }

    File file = File(item.localUrl);
    item.folderStorage = file.lengthSync();

    FileImage image = FileImage(File(item.localUrl));
    if(item.folderWidth == null || item.folderHeight == null){
      // 预先获取图片信息
      image
          .resolve(new ImageConfiguration())
          .addListener(new ImageStreamListener((ImageInfo info, bool _) {
        item.folderWidth = info.image.width;
        item.folderHeight = info.image.height;
        return item;
      }));
    }else{
      return item;
    }

  }

  Future<UploadMediaLibraryItemBean> _decodeVideo(
      UploadMediaLibraryItemBean item) async {
    if (item == null ||
        item.mediaType == null ||
        StringUtils.isEmpty(item.localUrl)) {
      return null;
    }
    File file = File(item.localUrl);
    Directory rootPath = await getTemporaryDirectory();
    Directory tempDirectory = new Directory('${rootPath.path}/imageTemp');
    if (!tempDirectory.existsSync()) {
      tempDirectory.createSync();
    }
    String tmpVideoCover = await VideoThumbnail.thumbnailFile(
      video: item.localUrl,
      thumbnailPath: tempDirectory?.path,
      imageFormat: ImageFormat.JPEG,
      maxWidth: 1920,
      quality: 100,
    );
    item.videoLocalCover = tmpVideoCover;
    //
    VideoPlayerController videoController = VideoPlayerController.file(file);
    await videoController.initialize();
    item.videoDuration = videoController?.value?.duration?.inSeconds;
    item.folderWidth = videoController?.value?.size?.width?.floor();
    item.folderHeight = videoController?.value?.size?.height?.floor();
    item.folderStorage = file.lengthSync();
    videoController.dispose();
    return item;
  }


  //多图上传
  Future<UploadMediaLibraryItemBean> _httpMultiFolder(
      UploadMediaLibraryItemBean item, {ValueChanged<int> onGetNewFileLength}) async {
    if (item == null) {
      return null;
    }
    if (item.isImage()) {
      try {
        item.netUrl = await VgMatisseUploadUtils.uploadSingleImageForFuture(
            item.localUrl,
            isNoCompress: false,
            onGetNewFileLength: onGetNewFileLength
        );
        if(StringUtils.isEmpty(item.folderName)){
          item.folderName=item?.getFolderNameStr() ?? "";
        }
        return item;
      } catch (e) {
        print("上传单图异常：$e");
      }
    }

    if (item.isVideo()) {
      try {
        VideoUploadSuccessBean successBean =
        await VgMatisseUploadUtils.uploadSingleVideoForFuture(
            item.localUrl);
        item.netUrl = successBean.url;
        item.videoid = successBean.videoid;
        item.folderName = VgMatisseUploadUtils.getVideoPath();
        if (!StringUtils.isEmpty(successBean.fileSize)) {
          item.folderStorage = int.parse(successBean.fileSize);
        }
        // if (StringUtils.isEmpty(successBean.coverUrl)) {
        item.videoNetCover =
        await VgMatisseUploadUtils.uploadSingleImageForFuture(
            item.videoLocalCover,
            isNoCompress: false);
        // } else {
        //   item.videoNetCover = successBean.coverUrl;
        // }
        return item;
      } catch (e) {
        print("MediaLibraryIndexService上传异常：$e");
      }
    }
    return null;
  }

  Future<UploadMediaLibraryItemBean> _httpFolder(
      UploadMediaLibraryItemBean item, {ValueChanged<int> onGetNewFileLength}) async {
    if (item == null) {
      return null;
    }
    if (item.isImage()) {
      try {
        item.netUrl = await VgMatisseUploadUtils.uploadSingleImageForFuture(
            item.localUrl,
            isNoCompress: false,
            onGetNewFileLength: onGetNewFileLength
        );
        if(StringUtils.isEmpty(item.folderName)){
          item.folderName=item?.getFolderNameStr() ?? "";
        }
        return _httpUpload(item);
      } catch (e) {
        print("上传单图异常：$e");
      }
    }

    if (item.isVideo()) {
      try {
        print("MediaLibraryIndexService try1111");
        VideoUploadSuccessBean successBean =
        await VgMatisseUploadUtils.uploadSingleVideoForFuture(
            item.localUrl);
        item.netUrl = successBean.url;
        item.videoid = successBean.videoid;
        print("MediaLibraryIndexService netUrl：" + item.netUrl);
        item.folderName = VgMatisseUploadUtils.getVideoPath();
        print("MediaLibraryIndexService folderName：" + item.folderName);
        if (!StringUtils.isEmpty(successBean.fileSize)) {
          item.folderStorage = int.parse(successBean.fileSize);
          print("MediaLibraryIndexService folderStorage：" + item.folderStorage.toString());
        }
        // if (StringUtils.isEmpty(successBean.coverUrl)) {
        item.videoNetCover =
        await VgMatisseUploadUtils.uploadSingleImageForFuture(
            item.videoLocalCover,
            isNoCompress: false);
        // } else {
        //   item.videoNetCover = successBean.coverUrl;
        // }
        print("MediaLibraryIndexService videoNetCover：" + item.videoNetCover);
        return _httpUpload(item);
      } catch (e) {
        print("MediaLibraryIndexService上传异常1：$e");
      }
    }
    return null;
  }

  Future<UploadMediaLibraryItemBean> _httpUpload(
      UploadMediaLibraryItemBean item) {
    if (item == null) {
      print("MediaLibraryIndexService上传失败：数据为空");
      return Future.error("数据为空");
    }
    if (item.mediaType == null ||
        StringUtils.isEmpty(item.getFolderNameStr())) {
      print("MediaLibraryIndexService上传失败：文件找不到");
      return Future.error("文件找不到");
    }
    Map<String, dynamic> paramsMap = {
      "authId": UserRepository.getInstance().authId ?? "",
      "picname": item.folderName ?? "",
      "picsize": item?.getSize() ?? "",
      "picstorage": item?.getStorage() ?? "",
      "picurl": item?.netUrl ?? "",
      "type": item?.mediaType?.getParamsValue() ?? "",
      "videopic": item?.videoNetCover ?? "",
      "videotime": item?.videoDuration ?? 0,
      "videoid": item?.videoid ?? "",
      "hsns": _hsns ?? null,
      "startday": _startDay ?? null,
      "endday": _endDay ?? null,
      "allflg": _allflg ?? null,
      "title": _title ?? null,
      "subtitle": _content ?? null,
      "waterflg": _waterflg ?? "01",
      "logoflg": _logoflg ?? "01",
    };

    print("准备上传测试参数: ${paramsMap}");
    Completer<UploadMediaLibraryItemBean> completer = Completer();
    // return;
    VgHttpUtils.get(UPLOAD_MEDIA_LIBRARY_WITH_TERMINAL_SETTINGS_API,
        params: paramsMap,
        callback: BaseCallback(onSuccess: (val) {
          // VgToastUtils.toast(AppMain.context, "上传成功");
          completer.complete(item);
        }, onError: (msg) {
          // VgToastUtils.toast(AppMain.context, msg);
          print("上传失败：111111" + msg);
          completer.completeError(msg);
          VgHudUtils.hide(_context);
          VgHudUtils.hide(AppMain.context);
          RouterUtils.pop(_context);
        }));
    return completer.future;
  }
}

class PicListItemBean{
  //视频、图片路径
  String picurl;
  //01 图片 02 视频
  String type;
  //视频、图片名称
  String picname;
  //视频、图片尺寸
  String picsize;
  //图片、视频大小
  String picstorage;
  //视频时长
  int videotime;
  //视频封面图
  String videopic;
  //视频id
  String videoid;

  PicListItemBean({this.picurl, this.type, this.picname, this.picsize,
      this.picstorage, this.videotime, this.videopic, this.videoid});

  Map toJson() => {
    "picurl": picurl,
    "type": type,
    "picname": picname,
    "picsize": picsize,
    "picstorage": picstorage,
    "videotime": videotime,
    "videopic": videopic,
    "videoid": videoid,
  };

}

class UploadMediaLibraryItemBean {
  //文件名称
  String folderName;

  //文件内存大小
  int folderStorage;

  int folderWidth;

  int folderHeight;

  //网络
  String netUrl;
  String localUrl;

  //媒体类型
  MediaType mediaType;

  //视频封面
  String videoNetCover;
  String videoLocalCover;
  //视频id
  String videoid;

  int videoDuration;

  String id;
  //字幕
  String subtitle;
  //字幕标题
  String title;
  //水印
  String waterflg;
  //机构logo
  String logoflg;

  UploadMediaLibraryItemBean({
    this.folderName,
    this.folderStorage,
    this.folderWidth,
    this.folderHeight,
    this.netUrl,
    this.localUrl,
    this.mediaType,
    this.videoDuration,
    this.videoLocalCover,
    this.videoid,
    this.id,
    this.title,
    this.subtitle,
    this.waterflg,
    this.logoflg,
  });

  bool isImage() {
    return mediaType == MediaType.image;
  }

  bool isVideo() {
    return mediaType == MediaType.video;
  }

  @override
  String toString() {
    return 'UploadMediaLibraryItemBean{folderName: $folderName, folderStorage: $folderStorage, folderWidth: $folderWidth, folderHeight: $folderHeight, netUrl: $netUrl, localUrl: $localUrl, mediaType: $mediaType, videoid: $videoid, videoNetCover: $videoNetCover, videoLocalCover: $videoLocalCover, videoDuration: $videoDuration}';
  }

  String getLocalClipPicUrl() {
    if (isImage()) {
      if (!localUrl.contains(".jpg")) {
        return localUrl + ".jpg";
      }
      return localUrl;
    }
    if (isVideo()) {
      return videoLocalCover;
    }
    return localUrl;
  }

  String getLocalPicUrl() {
    if (isImage()) {
      if (StringUtils.isNotEmpty(netUrl) && StringUtils.isEmpty(localUrl)) {
        return netUrl;
      } else {
        return localUrl;
      }
    }
    if (isVideo()) {
      return videoLocalCover;
    }
    return localUrl;
  }

  String getPicOrVideoUrl() {
    if (isImage()) {
      if (StringUtils.isNotEmpty(netUrl) && StringUtils.isEmpty(localUrl)) {
        return netUrl;
      } else {
        return localUrl;
      }
    }
    return localUrl;
  }

  String getFolderNameStr() {
    String url = netUrl;
    if (StringUtils.isEmpty(url)) {
      return null;
    }
    List<String> list = url.split("/");
    if (list == null || list.isEmpty) {
      return null;
    }
    return list.elementAt(list.length - 1);
  }

  String getSize() {
    if (folderWidth == null || folderHeight == null) {
      return null;
    }
    return "$folderWidth*$folderHeight";
  }

  String getStorage() {
    if (folderStorage == null) {
      return null;
    }
    return (folderStorage / 1024).floor().toString();
  }

  ///上传状态
  UploadStatus _status;

  UploadStatus get status => _status;

  set status(UploadStatus value) {
    _status = value;
  }

  ///进度
  double _progress;

  double get progress => _progress;

  set progress(double value) {
    _progress = value;
  }
}

enum MediaType { image, video }

extension MediaTypeExtension on MediaType {
  String getParamsValue() {
    switch (this) {
      case MediaType.image:
        return "01";
      case MediaType.video:
        return "02";
    }
    return null;
  }
}
